package com.qianxx.base.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

/**
 * 图片处理类： 功能： 1、压缩图片 2、图片旋转（待测试） 3、图片保存
 *
 * @author 哈哈先生
 * @version 1.0
 */
public class ZoomBitmap {
    public static final String SUB_PATH_IMG = "Draw/img";// 图片子路径

    private static String newPath;// 新路径（完整路径）

    private static String picName;// 文件名

    public static String getNewPath() {
        return newPath;
    }

    public static String getImageName() {
        return System.currentTimeMillis() + ".jpg";
    }

    /**
     * 获取压缩保存后的图片地址 方法功能： 1、压缩图片 2、构建新图片即将保存的新路径 3、判断图片是否需要旋转，如果需要 则将图片旋转 4、保存压缩后的图片 5、返回图片保存的新地址
     *
     * @param pathName       原图片的路径+文件全名 例子:"path/filename.jpg"
     * @param bitmapMaxWidth 图片要压缩到的宽度，至于高度会按照图片原比例大小进行压缩
     * @return 压缩后保存到本地的新图片的地址 return 例子："path/SUB_PATH_IMG/filename.jpg"
     * @throws IOException
     */
    public static String getSmallBitmap(String pathName, int bitmapMaxWidth)
            throws Exception {
        String[] split = pathName.split("/");
        String name = split[split.length - 1];
        ZoomBitmap.picName = name;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int reqHeight = 0;
        int reqWidth = bitmapMaxWidth;
        if (width > reqWidth) {
            reqHeight = (reqWidth * height) / width;
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, reqHeight, reqWidth);
        } else {
            options.inSampleSize = 1;
            reqHeight = height;
            reqWidth = width;
        }
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
        Log.e("ZoomBitmap", "reqWidth->" + reqWidth + "---reqHeight->" + reqHeight);
        Bitmap bbb = compressImage(Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false));
        Bitmap bitmapRotate = reviewPicRotate(bbb, pathName);
        return saveImg(bitmapRotate, ZoomBitmap.picName);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    private static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            options -= 10;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 获取图片文件的信息，是否旋转了90度，如果是则反转
     *
     * @param bitmap 需要旋转的图片
     * @param path   图片的路径
     */
    public static Bitmap reviewPicRotate(Bitmap bitmap, String path) {
        int degree = getPicRotate(path);
        if (degree > 0) {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            m.setRotate(degree); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片
        }
        return bitmap;
    }

    /**
     * 读取图片文件旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片旋转的角度
     */
    public static int getPicRotate(String path) {
        int degree = 0;
        try {
            if (TextUtils.isEmpty(path)) {
                return -1;
            }
            ExifInterface exifInterface = new ExifInterface(path);

            int orientation =
                    exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 保存图片
     *
     * @param bitmap 需要保存的图片
     * @param name   图片保存的名称
     * @return 返回保存后的图片地址
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static String saveImg(Bitmap bitmap, String name)
            throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/" + SUB_PATH_IMG + "/";
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        File mediaFile = new File(path, name);
        mediaFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(mediaFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
        bitmap.recycle();
        bitmap = null;
        System.gc();
        newPath = mediaFile.getPath();
        Log.e("ZoomBitmap", "压缩后的图片 :" + newPath);
        return newPath;
    }

    public static String bitmap2FilePath(Bitmap bitmap, String name)
            throws Exception {
        String path = Environment.getExternalStorageDirectory() + "/"
                + SUB_PATH_IMG + "/";
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        File mediaFile = new File(path, name);
        mediaFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(mediaFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
        bitmap.recycle();
        bitmap = null;
        System.gc();
        newPath = mediaFile.getPath();
        Log.e("ZoomBitmap", "压缩后的图片 :" + newPath);
        return newPath;
    }

    public static String bitmap2FilePath2(Bitmap bitmap, String name)
            throws Exception {
        String path = Environment.getExternalStorageDirectory() + "/"
                + SUB_PATH_IMG + "/";
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        File mediaFile = new File(path, name);
        mediaFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(mediaFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
//        bitmap.recycle();
//        bitmap = null;
        System.gc();
        newPath = mediaFile.getPath();
        Log.e("ZoomBitmap", "压缩后的图片 :" + newPath);
        return newPath;
    }
}
